package com.wanxi.udp.demo4广播;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

/**
 * 广播消息接收端
 */
public class UDPBroadcastReceive {
    public static void main(String[] args) throws IOException {

        String id = "夏禹";
        System.out.println(id + "广播接收端启动..");
        // 创建接收端socket。
        // 这试试用MulticastSocket看会怎么样
//        MulticastSocket datagramSocket = new MulticastSocket(10000);
//        datagramSocket.joinGroup(InetAddress.getByName("255.255.255.255"));
//        InetAddress byName = InetAddress.getByName("255.255.255.255");
        DatagramSocket datagramSocket = new DatagramSocket(10001);
        // 创建需要发送的数据包
        DatagramPacket datagramPacket = new DatagramPacket(new byte[1024], 1024);
        // 接收数据
        datagramSocket.receive(datagramPacket);
        byte[] data = datagramPacket.getData();
        int length = datagramPacket.getLength();
        String message = new String(data, 0, length);

        System.out.println("收到的消息：" + message);

        datagramSocket.close();
    }
}
